Passed
Branch wavefile-rw (f95614)
by Rafael S.
02:53
created

WaveFileParser.validateSampleRate_   A

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 2
1
/*
2
 * Copyright (c) 2017-2019 Rafael da Silva Rocha.
3
 *
4
 * Permission is hereby granted, free of charge, to any person obtaining
5
 * a copy of this software and associated documentation files (the
6
 * "Software"), to deal in the Software without restriction, including
7
 * without limitation the rights to use, copy, modify, merge, publish,
8
 * distribute, sublicense, and/or sell copies of the Software, and to
9
 * permit persons to whom the Software is furnished to do so, subject to
10
 * the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be
13
 * included in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
25
/**
26
 * @fileoverview The WaveFileParser class.
27
 * @see https://github.com/rochars/wavefile
28
 */
29
30
import RIFFFile from './riff-file';
31
import writeString from './write-string';
32
import validateNumChannels from './validate-num-channels'; 
33
import validateSampleRate from './validate-sample-rate';
34
import {packTo, packStringTo, packString, pack} from 'byte-data';
35
36
/**
37
 * A class to read and write wav files.
38
 */
39
export default class WaveFileParser extends RIFFFile {
40
41
  constructor() {
42
    super();
43
    /**
44
     * Audio formats.
45
     * Formats not listed here should be set to 65534,
46
     * the code for WAVE_FORMAT_EXTENSIBLE
47
     * @enum {number}
48
     * @protected
49
     */
50
    this.WAV_AUDIO_FORMATS = {
51
      '4': 17,
52
      '8': 1,
53
      '8a': 6,
54
      '8m': 7,
55
      '16': 1,
56
      '24': 1,
57
      '32': 1,
58
      '32f': 3,
59
      '64': 3
60
    };
61
    /**
62
     * The data of the 'fmt' chunk.
63
     * @type {!Object<string, *>}
64
     */
65
    this.fmt = {
66
      /** @type {string} */
67
      chunkId: '',
68
      /** @type {number} */
69
      chunkSize: 0,
70
      /** @type {number} */
71
      audioFormat: 0,
72
      /** @type {number} */
73
      numChannels: 0,
74
      /** @type {number} */
75
      sampleRate: 0,
76
      /** @type {number} */
77
      byteRate: 0,
78
      /** @type {number} */
79
      blockAlign: 0,
80
      /** @type {number} */
81
      bitsPerSample: 0,
82
      /** @type {number} */
83
      cbSize: 0,
84
      /** @type {number} */
85
      validBitsPerSample: 0,
86
      /** @type {number} */
87
      dwChannelMask: 0,
88
      /**
89
       * 4 32-bit values representing a 128-bit ID
90
       * @type {!Array<number>}
91
       */
92
      subformat: []
93
    };
94
    /**
95
     * The data of the 'fact' chunk.
96
     * @type {!Object<string, *>}
97
     */
98
    this.fact = {
99
      /** @type {string} */
100
      chunkId: '',
101
      /** @type {number} */
102
      chunkSize: 0,
103
      /** @type {number} */
104
      dwSampleLength: 0
105
    };
106
    /**
107
     * The data of the 'cue ' chunk.
108
     * @type {!Object<string, *>}
109
     */
110
    this.cue = {
111
      /** @type {string} */
112
      chunkId: '',
113
      /** @type {number} */
114
      chunkSize: 0,
115
      /** @type {number} */
116
      dwCuePoints: 0,
117
      /** @type {!Array<!Object>} */
118
      points: [],
119
    };
120
    /**
121
     * The data of the 'smpl' chunk.
122
     * @type {!Object<string, *>}
123
     */
124
    this.smpl = {
125
      /** @type {string} */
126
      chunkId: '',
127
      /** @type {number} */
128
      chunkSize: 0,
129
      /** @type {number} */
130
      dwManufacturer: 0,
131
      /** @type {number} */
132
      dwProduct: 0,
133
      /** @type {number} */
134
      dwSamplePeriod: 0,
135
      /** @type {number} */
136
      dwMIDIUnityNote: 0,
137
      /** @type {number} */
138
      dwMIDIPitchFraction: 0,
139
      /** @type {number} */
140
      dwSMPTEFormat: 0,
141
      /** @type {number} */
142
      dwSMPTEOffset: 0,
143
      /** @type {number} */
144
      dwNumSampleLoops: 0,
145
      /** @type {number} */
146
      dwSamplerData: 0,
147
      /** @type {!Array<!Object>} */
148
      loops: []
149
    };
150
    /**
151
     * The data of the 'bext' chunk.
152
     * @type {!Object<string, *>}
153
     */
154
    this.bext = {
155
      /** @type {string} */
156
      chunkId: '',
157
      /** @type {number} */
158
      chunkSize: 0,
159
      /** @type {string} */
160
      description: '', //256
161
      /** @type {string} */
162
      originator: '', //32
163
      /** @type {string} */
164
      originatorReference: '', //32
165
      /** @type {string} */
166
      originationDate: '', //10
167
      /** @type {string} */
168
      originationTime: '', //8
169
      /**
170
       * 2 32-bit values, timeReference high and low
171
       * @type {!Array<number>}
172
       */
173
      timeReference: [0, 0],
174
      /** @type {number} */
175
      version: 0, //WORD
176
      /** @type {string} */
177
      UMID: '', // 64 chars
178
      /** @type {number} */
179
      loudnessValue: 0, //WORD
180
      /** @type {number} */
181
      loudnessRange: 0, //WORD
182
      /** @type {number} */
183
      maxTruePeakLevel: 0, //WORD
184
      /** @type {number} */
185
      maxMomentaryLoudness: 0, //WORD
186
      /** @type {number} */
187
      maxShortTermLoudness: 0, //WORD
188
      /** @type {string} */
189
      reserved: '', //180
190
      /** @type {string} */
191
      codingHistory: '' // string, unlimited
192
    };
193
    /**
194
     * The data of the 'ds64' chunk.
195
     * Used only with RF64 files.
196
     * @type {!Object<string, *>}
197
     */
198
    this.ds64 = {
199
      /** @type {string} */
200
      chunkId: '',
201
      /** @type {number} */
202
      chunkSize: 0,
203
      /** @type {number} */
204
      riffSizeHigh: 0, // DWORD
205
      /** @type {number} */
206
      riffSizeLow: 0, // DWORD
207
      /** @type {number} */
208
      dataSizeHigh: 0, // DWORD
209
      /** @type {number} */
210
      dataSizeLow: 0, // DWORD
211
      /** @type {number} */
212
      originationTime: 0, // DWORD
213
      /** @type {number} */
214
      sampleCountHigh: 0, // DWORD
215
      /** @type {number} */
216
      sampleCountLow: 0 // DWORD
217
      /** @type {number} */
218
      //'tableLength': 0, // DWORD
219
      /** @type {!Array<number>} */
220
      //'table': []
221
    };
222
    /**
223
     * The data of the 'data' chunk.
224
     * @type {!Object<string, *>}
225
     */
226
    this.data = {
227
      /** @type {string} */
228
      chunkId: '',
229
      /** @type {number} */
230
      chunkSize: 0,
231
      /** @type {!Uint8Array} */
232
      samples: new Uint8Array(0)
233
    };
234
    /**
235
     * The data of the 'LIST' chunks.
236
     * Each item in this list look like this:
237
     *  {
238
     *      chunkId: '',
239
     *      chunkSize: 0,
240
     *      format: '',
241
     *      subChunks: []
242
     *   }
243
     * @type {!Array<!Object>}
244
     */
245
    this.LIST = [];
246
    /**
247
     * The data of the 'junk' chunk.
248
     * @type {!Object<string, *>}
249
     */
250
    this.junk = {
251
      /** @type {string} */
252
      chunkId: '',
253
      /** @type {number} */
254
      chunkSize: 0,
255
      /** @type {!Array<number>} */
256
      chunkData: []
257
    };
258
    /**
259
     * The bit depth code according to the samples.
260
     * @type {string}
261
     */
262
    this.bitDepth = '0';
263
    /**
264
     * @type {!Object}
265
     * @protected
266
     */
267
    this.dataType = {};
268
  }
269
270
  /**
271
   * Set up the WaveFileParser object from a byte buffer.
272
   * @param {!Uint8Array} wavBuffer The buffer.
273
   * @param {boolean=} samples True if the samples should be loaded.
274
   * @throws {Error} If container is not RIFF, RIFX or RF64.
275
   * @throws {Error} If format is not WAVE.
276
   * @throws {Error} If no 'fmt ' chunk is found.
277
   * @throws {Error} If no 'data' chunk is found.
278
   */
279
  readBuffer(wavBuffer, samples=true) {
280
    this.clearHeader();
281
    this.head_ = 0;
282
    this.readRIFFChunk(wavBuffer);
283
    if (this.format != 'WAVE') {
284
      throw Error('Could not find the "WAVE" format identifier');
285
    }
286
    this.setSignature(wavBuffer);
287
    this.readDs64Chunk_(wavBuffer);
288
    this.readFmtChunk_(wavBuffer);
289
    this.readFactChunk_(wavBuffer);
290
    this.readBextChunk_(wavBuffer);
291
    this.readCueChunk_(wavBuffer);
292
    this.readSmplChunk_(wavBuffer);
293
    this.readDataChunk_(wavBuffer, samples);
294
    this.readJunkChunk_(wavBuffer);
295
    this.readLISTChunk_(wavBuffer);
296
    this.bitDepthFromFmt_();
297
    this.updateDataType();
298
  }
299
300
  /**
301
   * Return a byte buffer representig the WaveFileParser object as a .wav file.
302
   * The return value of this method can be written straight to disk.
303
   * @return {!Uint8Array} A wav file.
304
   * @throws {Error} If bit depth is invalid.
305
   * @throws {Error} If the number of channels is invalid.
306
   * @throws {Error} If the sample rate is invalid.
307
   */
308
  writeBuffer() {
309
    this.validateWavHeader();
310
    return this.writeWavBuffer_();
311
  }
312
313
  /**
314
   * Reset some attributes of the object.
315
   * @protected
316
   */
317
  clearHeader() {
318
    this.fmt.cbSize = 0;
319
    this.fmt.validBitsPerSample = 0;
320
    this.fact.chunkId = '';
321
    this.ds64.chunkId = '';
322
  }
323
324
  /**
325
   * Validate the header of the file.
326
   * @throws {Error} If bit depth is invalid.
327
   * @throws {Error} If the number of channels is invalid.
328
   * @throws {Error} If the sample rate is invalid.
329
   * @protected
330
   */
331
  validateWavHeader() {
332
    this.validateBitDepth_();
333
    if (!validateNumChannels(this.fmt.numChannels, this.fmt.bitsPerSample)) {
334
      throw new Error('Invalid number of channels.');
335
    }
336
    if (!validateSampleRate(
337
        this.fmt.numChannels, this.fmt.bitsPerSample, this.fmt.sampleRate)) {
338
      throw new Error('Invalid sample rate.');
339
    }
340
  }
341
342
  /**
343
   * Update the type definition used to read and write the samples.
344
   * @protected
345
   */
346
  updateDataType() {
347
    this.dataType = {
348
      bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,
349
      fp: this.bitDepth == '32f' || this.bitDepth == '64',
350
      signed: this.bitDepth != '8',
351
      be: this.container == 'RIFX'
352
    };
353
    if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {
354
      this.dataType.bits = 8;
355
      this.dataType.signed = false;
356
    }
357
  }
358
359
  /**
360
   * Set the string code of the bit depth based on the 'fmt ' chunk.
361
   * @private
362
   */
363
  bitDepthFromFmt_() {
364
    if (this.fmt.audioFormat === 3 && this.fmt.bitsPerSample === 32) {
365
      this.bitDepth = '32f';
366
    } else if (this.fmt.audioFormat === 6) {
367
      this.bitDepth = '8a';
368
    } else if (this.fmt.audioFormat === 7) {
369
      this.bitDepth = '8m';
370
    } else {
371
      this.bitDepth = this.fmt.bitsPerSample.toString();
372
    }
373
  }
374
375
  /**
376
   * Return a .wav file byte buffer with the data from the WaveFileParser object.
377
   * The return value of this method can be written straight to disk.
378
   * @return {!Uint8Array} The wav file bytes.
379
   * @private
380
   */
381
  writeWavBuffer_() {
382
    this.uInt16_.be = this.container === 'RIFX';
383
    this.uInt32_.be = this.uInt16_.be;
384
    /** @type {!Array<!Array<number>>} */
385
    let fileBody = [
386
      this.getJunkBytes_(),
387
      this.getDs64Bytes_(),
388
      this.getBextBytes_(),
389
      this.getFmtBytes_(),
390
      this.getFactBytes_(),
391
      packString(this.data.chunkId),
392
      pack(this.data.samples.length, this.uInt32_),
393
      this.data.samples,
394
      this.getCueBytes_(),
395
      this.getSmplBytes_(),
396
      this.getLISTBytes_()
397
    ];
398
    /** @type {number} */
399
    let fileBodyLength = 0;
400
    for (let i=0; i<fileBody.length; i++) {
401
      fileBodyLength += fileBody[i].length;
402
    }
403
    /** @type {!Uint8Array} */
404
    let file = new Uint8Array(fileBodyLength + 12);
405
    /** @type {number} */
406
    let index = 0;
407
    index = packStringTo(this.container, file, index);
408
    index = packTo(fileBodyLength + 4, this.uInt32_, file, index);
409
    index = packStringTo(this.format, file, index);
410
    for (let i=0; i<fileBody.length; i++) {
411
      file.set(fileBody[i], index);
412
      index += fileBody[i].length;
413
    }
414
    return file;
415
  }
416
417
  /**
418
   * Return the bytes of the 'bext' chunk.
419
   * @private
420
   */
421
  getBextBytes_() {
422
    /** @type {!Array<number>} */
423
    let bytes = [];
424
    this.enforceBext_();
425
    if (this.bext.chunkId) {
426
      this.bext.chunkSize = 602 + this.bext.codingHistory.length;
427
      bytes = bytes.concat(
428
        packString(this.bext.chunkId),
429
        pack(602 + this.bext.codingHistory.length, this.uInt32_),
430
        writeString(this.bext.description, 256),
431
        writeString(this.bext.originator, 32),
432
        writeString(this.bext.originatorReference, 32),
433
        writeString(this.bext.originationDate, 10),
434
        writeString(this.bext.originationTime, 8),
435
        pack(this.bext.timeReference[0], this.uInt32_),
436
        pack(this.bext.timeReference[1], this.uInt32_),
437
        pack(this.bext.version, this.uInt16_),
438
        writeString(this.bext.UMID, 64),
439
        pack(this.bext.loudnessValue, this.uInt16_),
440
        pack(this.bext.loudnessRange, this.uInt16_),
441
        pack(this.bext.maxTruePeakLevel, this.uInt16_),
442
        pack(this.bext.maxMomentaryLoudness, this.uInt16_),
443
        pack(this.bext.maxShortTermLoudness, this.uInt16_),
444
        writeString(this.bext.reserved, 180),
445
        writeString(
446
          this.bext.codingHistory, this.bext.codingHistory.length));
447
    }
448
    return bytes;
449
  }
450
451
  /**
452
   * Make sure a 'bext' chunk is created if BWF data was created in a file.
453
   * @private
454
   */
455
  enforceBext_() {
456
    for (let prop in this.bext) {
457
      if (this.bext.hasOwnProperty(prop)) {
458
        if (this.bext[prop] && prop != 'timeReference') {
459
          this.bext.chunkId = 'bext';
460
          break;
461
        }
462
      }
463
    }
464
    if (this.bext.timeReference[0] || this.bext.timeReference[1]) {
465
      this.bext.chunkId = 'bext';
466
    }
467
  }
468
469
  /**
470
   * Return the bytes of the 'ds64' chunk.
471
   * @return {!Array<number>} The 'ds64' chunk bytes.
472
   * @private
473
   */
474
  getDs64Bytes_() {
475
    /** @type {!Array<number>} */
476
    let bytes = [];
477
    if (this.ds64.chunkId) {
478
      bytes = bytes.concat(
479
        packString(this.ds64.chunkId),
480
        pack(this.ds64.chunkSize, this.uInt32_),
481
        pack(this.ds64.riffSizeHigh, this.uInt32_),
482
        pack(this.ds64.riffSizeLow, this.uInt32_),
483
        pack(this.ds64.dataSizeHigh, this.uInt32_),
484
        pack(this.ds64.dataSizeLow, this.uInt32_),
485
        pack(this.ds64.originationTime, this.uInt32_),
486
        pack(this.ds64.sampleCountHigh, this.uInt32_),
487
        pack(this.ds64.sampleCountLow, this.uInt32_));
488
    }
489
    //if (this.ds64.tableLength) {
490
    //  ds64Bytes = ds64Bytes.concat(
491
    //    pack(this.ds64.tableLength, this.uInt32_),
492
    //    this.ds64.table);
493
    //}
494
    return bytes;
495
  }
496
497
  /**
498
   * Return the bytes of the 'cue ' chunk.
499
   * @return {!Array<number>} The 'cue ' chunk bytes.
500
   * @private
501
   */
502
  getCueBytes_() {
503
    /** @type {!Array<number>} */
504
    let bytes = [];
505
    if (this.cue.chunkId) {
506
      /** @type {!Array<number>} */
507
      let cuePointsBytes = this.getCuePointsBytes_();
508
      bytes = bytes.concat(
509
        packString(this.cue.chunkId),
510
        pack(cuePointsBytes.length + 4, this.uInt32_),
511
        pack(this.cue.dwCuePoints, this.uInt32_),
512
        cuePointsBytes);
513
    }
514
    return bytes;
515
  }
516
517
  /**
518
   * Return the bytes of the 'cue ' points.
519
   * @return {!Array<number>} The 'cue ' points as an array of bytes.
520
   * @private
521
   */
522
  getCuePointsBytes_() {
523
    /** @type {!Array<number>} */
524
    let points = [];
525
    for (let i=0; i<this.cue.dwCuePoints; i++) {
526
      points = points.concat(
527
        pack(this.cue.points[i].dwName, this.uInt32_),
528
        pack(this.cue.points[i].dwPosition, this.uInt32_),
529
        packString(this.cue.points[i].fccChunk),
530
        pack(this.cue.points[i].dwChunkStart, this.uInt32_),
531
        pack(this.cue.points[i].dwBlockStart, this.uInt32_),
532
        pack(this.cue.points[i].dwSampleOffset, this.uInt32_));
533
    }
534
    return points;
535
  }
536
537
  /**
538
   * Return the bytes of the 'smpl' chunk.
539
   * @return {!Array<number>} The 'smpl' chunk bytes.
540
   * @private
541
   */
542
  getSmplBytes_() {
543
    /** @type {!Array<number>} */
544
    let bytes = [];
545
    if (this.smpl.chunkId) {
546
      /** @type {!Array<number>} */
547
      let smplLoopsBytes = this.getSmplLoopsBytes_();
548
      bytes = bytes.concat(
549
        packString(this.smpl.chunkId),
550
        pack(smplLoopsBytes.length + 36, this.uInt32_),
551
        pack(this.smpl.dwManufacturer, this.uInt32_),
552
        pack(this.smpl.dwProduct, this.uInt32_),
553
        pack(this.smpl.dwSamplePeriod, this.uInt32_),
554
        pack(this.smpl.dwMIDIUnityNote, this.uInt32_),
555
        pack(this.smpl.dwMIDIPitchFraction, this.uInt32_),
556
        pack(this.smpl.dwSMPTEFormat, this.uInt32_),
557
        pack(this.smpl.dwSMPTEOffset, this.uInt32_),
558
        pack(this.smpl.dwNumSampleLoops, this.uInt32_),
559
        pack(this.smpl.dwSamplerData, this.uInt32_),
560
        smplLoopsBytes);
561
    }
562
    return bytes;
563
  }
564
565
  /**
566
   * Return the bytes of the 'smpl' loops.
567
   * @return {!Array<number>} The 'smpl' loops as an array of bytes.
568
   * @private
569
   */
570
  getSmplLoopsBytes_() {
571
    /** @type {!Array<number>} */
572
    let loops = [];
573
    for (let i=0; i<this.smpl.dwNumSampleLoops; i++) {
574
      loops = loops.concat(
575
        pack(this.smpl.loops[i].dwName, this.uInt32_),
576
        pack(this.smpl.loops[i].dwType, this.uInt32_),
577
        pack(this.smpl.loops[i].dwStart, this.uInt32_),
578
        pack(this.smpl.loops[i].dwEnd, this.uInt32_),
579
        pack(this.smpl.loops[i].dwFraction, this.uInt32_),
580
        pack(this.smpl.loops[i].dwPlayCount, this.uInt32_));
581
    }
582
    return loops;
583
  }
584
585
  /**
586
   * Return the bytes of the 'fact' chunk.
587
   * @return {!Array<number>} The 'fact' chunk bytes.
588
   * @private
589
   */
590
  getFactBytes_() {
591
    /** @type {!Array<number>} */
592
    let bytes = [];
593
    if (this.fact.chunkId) {
594
      bytes = bytes.concat(
595
        packString(this.fact.chunkId),
596
        pack(this.fact.chunkSize, this.uInt32_),
597
        pack(this.fact.dwSampleLength, this.uInt32_));
598
    }
599
    return bytes;
600
  }
601
602
  /**
603
   * Return the bytes of the 'fmt ' chunk.
604
   * @return {!Array<number>} The 'fmt' chunk bytes.
605
   * @throws {Error} if no 'fmt ' chunk is present.
606
   * @private
607
   */
608
  getFmtBytes_() {
609
    /** @type {!Array<number>} */
610
    let fmtBytes = [];
611
    if (this.fmt.chunkId) {
612
      return fmtBytes.concat(
613
        packString(this.fmt.chunkId),
614
        pack(this.fmt.chunkSize, this.uInt32_),
615
        pack(this.fmt.audioFormat, this.uInt16_),
616
        pack(this.fmt.numChannels, this.uInt16_),
617
        pack(this.fmt.sampleRate, this.uInt32_),
618
        pack(this.fmt.byteRate, this.uInt32_),
619
        pack(this.fmt.blockAlign, this.uInt16_),
620
        pack(this.fmt.bitsPerSample, this.uInt16_),
621
        this.getFmtExtensionBytes_());
622
    }
623
    throw Error('Could not find the "fmt " chunk');
624
  }
625
626
  /**
627
   * Return the bytes of the fmt extension fields.
628
   * @return {!Array<number>} The fmt extension bytes.
629
   * @private
630
   */
631
  getFmtExtensionBytes_() {
632
    /** @type {!Array<number>} */
633
    let extension = [];
634
    if (this.fmt.chunkSize > 16) {
635
      extension = extension.concat(
636
        pack(this.fmt.cbSize, this.uInt16_));
637
    }
638
    if (this.fmt.chunkSize > 18) {
639
      extension = extension.concat(
640
        pack(this.fmt.validBitsPerSample, this.uInt16_));
641
    }
642
    if (this.fmt.chunkSize > 20) {
643
      extension = extension.concat(
644
        pack(this.fmt.dwChannelMask, this.uInt32_));
645
    }
646
    if (this.fmt.chunkSize > 24) {
647
      extension = extension.concat(
648
        pack(this.fmt.subformat[0], this.uInt32_),
649
        pack(this.fmt.subformat[1], this.uInt32_),
650
        pack(this.fmt.subformat[2], this.uInt32_),
651
        pack(this.fmt.subformat[3], this.uInt32_));
652
    }
653
    return extension;
654
  }
655
656
  /**
657
   * Return the bytes of the 'LIST' chunk.
658
   * @return {!Array<number>} The 'LIST' chunk bytes.
659
   * @private
660
   */
661
  getLISTBytes_() {
662
    /** @type {!Array<number>} */
663
    let bytes = [];
664
    for (let i=0; i<this.LIST.length; i++) {
665
      /** @type {!Array<number>} */
666
      let subChunksBytes = this.getLISTSubChunksBytes_(
667
          this.LIST[i].subChunks, this.LIST[i].format);
668
      bytes = bytes.concat(
669
        packString(this.LIST[i].chunkId),
670
        pack(subChunksBytes.length + 4, this.uInt32_),
671
        packString(this.LIST[i].format),
672
        subChunksBytes);
673
    }
674
    return bytes;
675
  }
676
677
  /**
678
   * Return the bytes of the sub chunks of a 'LIST' chunk.
679
   * @param {!Array<!Object>} subChunks The 'LIST' sub chunks.
680
   * @param {string} format The format of the 'LIST' chunk.
681
   *    Currently supported values are 'adtl' or 'INFO'.
682
   * @return {!Array<number>} The sub chunk bytes.
683
   * @private
684
   */
685
  getLISTSubChunksBytes_(subChunks, format) {
686
    /** @type {!Array<number>} */
687
    let bytes = [];
688
    for (let i=0; i<subChunks.length; i++) {
689
      if (format == 'INFO') {
690
        bytes = bytes.concat(
691
          packString(subChunks[i].chunkId),
692
          pack(subChunks[i].value.length + 1, this.uInt32_),
693
          writeString(
694
            subChunks[i].value, subChunks[i].value.length));
695
        bytes.push(0);
696
      } else if (format == 'adtl') {
697
        if (['labl', 'note'].indexOf(subChunks[i].chunkId) > -1) {
698
          bytes = bytes.concat(
699
            packString(subChunks[i].chunkId),
700
            pack(
701
              subChunks[i].value.length + 4 + 1, this.uInt32_),
702
            pack(subChunks[i].dwName, this.uInt32_),
703
            writeString(
704
              subChunks[i].value,
705
              subChunks[i].value.length));
706
          bytes.push(0);
707
        } else if (subChunks[i].chunkId == 'ltxt') {
708
          bytes = bytes.concat(
709
            this.getLtxtChunkBytes_(subChunks[i]));
710
        }
711
      }
712
      if (bytes.length % 2) {
713
        bytes.push(0);
714
      }
715
    }
716
    return bytes;
717
  }
718
719
  /**
720
   * Return the bytes of a 'ltxt' chunk.
721
   * @param {!Object} ltxt the 'ltxt' chunk.
722
   * @private
723
   */
724
  getLtxtChunkBytes_(ltxt) {
725
    return [].concat(
726
      packString(ltxt.chunkId),
727
      pack(ltxt.value.length + 20, this.uInt32_),
728
      pack(ltxt.dwName, this.uInt32_),
729
      pack(ltxt.dwSampleLength, this.uInt32_),
730
      pack(ltxt.dwPurposeID, this.uInt32_),
731
      pack(ltxt.dwCountry, this.uInt16_),
732
      pack(ltxt.dwLanguage, this.uInt16_),
733
      pack(ltxt.dwDialect, this.uInt16_),
734
      pack(ltxt.dwCodePage, this.uInt16_),
735
      writeString(ltxt.value, ltxt.value.length));
736
  }
737
738
  /**
739
   * Return the bytes of the 'junk' chunk.
740
   * @private
741
   */
742
  getJunkBytes_() {
743
    /** @type {!Array<number>} */
744
    let bytes = [];
745
    if (this.junk.chunkId) {
746
      return bytes.concat(
747
        packString(this.junk.chunkId),
748
        pack(this.junk.chunkData.length, this.uInt32_),
749
        this.junk.chunkData);
750
    }
751
    return bytes;
752
  }
753
754
  /**
755
   * Read the 'fmt ' chunk of a wave file.
756
   * @param {!Uint8Array} buffer The wav file buffer.
757
   * @throws {Error} If no 'fmt ' chunk is found.
758
   * @private
759
   */
760
  readFmtChunk_(buffer) {
761
    /** @type {?Object} */
762
    let chunk = this.findChunk('fmt ');
763
    if (chunk) {
764
      this.head_ = chunk.chunkData.start;
765
      this.fmt.chunkId = chunk.chunkId;
766
      this.fmt.chunkSize = chunk.chunkSize;
767
      this.fmt.audioFormat = this.readNumber(buffer, this.uInt16_);
768
      this.fmt.numChannels = this.readNumber(buffer, this.uInt16_);
769
      this.fmt.sampleRate = this.readNumber(buffer, this.uInt32_);
770
      this.fmt.byteRate = this.readNumber(buffer, this.uInt32_);
771
      this.fmt.blockAlign = this.readNumber(buffer, this.uInt16_);
772
      this.fmt.bitsPerSample = this.readNumber(buffer, this.uInt16_);
773
      this.readFmtExtension_(buffer);
774
    } else {
775
      throw Error('Could not find the "fmt " chunk');
776
    }
777
  }
778
779
  /**
780
   * Read the 'fmt ' chunk extension.
781
   * @param {!Uint8Array} buffer The wav file buffer.
782
   * @private
783
   */
784
  readFmtExtension_(buffer) {
785
    if (this.fmt.chunkSize > 16) {
786
      this.fmt.cbSize = this.readNumber(buffer, this.uInt16_);
787
      if (this.fmt.chunkSize > 18) {
788
        this.fmt.validBitsPerSample = this.readNumber(buffer, this.uInt16_);
789
        if (this.fmt.chunkSize > 20) {
790
          this.fmt.dwChannelMask = this.readNumber(buffer, this.uInt32_);
791
          this.fmt.subformat = [
792
            this.readNumber(buffer, this.uInt32_),
793
            this.readNumber(buffer, this.uInt32_),
794
            this.readNumber(buffer, this.uInt32_),
795
            this.readNumber(buffer, this.uInt32_)];
796
        }
797
      }
798
    }
799
  }
800
801
  /**
802
   * Read the 'fact' chunk of a wav file.
803
   * @param {!Uint8Array} buffer The wav file buffer.
804
   * @private
805
   */
806
  readFactChunk_(buffer) {
807
    /** @type {?Object} */
808
    let chunk = this.findChunk('fact');
809
    if (chunk) {
810
      this.head_ = chunk.chunkData.start;
811
      this.fact.chunkId = chunk.chunkId;
812
      this.fact.chunkSize = chunk.chunkSize;
813
      this.fact.dwSampleLength = this.readNumber(buffer, this.uInt32_);
814
    }
815
  }
816
817
  /**
818
   * Read the 'cue ' chunk of a wave file.
819
   * @param {!Uint8Array} buffer The wav file buffer.
820
   * @private
821
   */
822
  readCueChunk_(buffer) {
823
    /** @type {?Object} */
824
    let chunk = this.findChunk('cue ');
825
    if (chunk) {
826
      this.head_ = chunk.chunkData.start;
827
      this.cue.chunkId = chunk.chunkId;
828
      this.cue.chunkSize = chunk.chunkSize;
829
      this.cue.dwCuePoints = this.readNumber(buffer, this.uInt32_);
830
      for (let i = 0; i < this.cue.dwCuePoints; i++) {
831
        this.cue.points.push({
832
          dwName: this.readNumber(buffer, this.uInt32_),
833
          dwPosition: this.readNumber(buffer, this.uInt32_),
834
          fccChunk: this.readString(buffer, 4),
835
          dwChunkStart: this.readNumber(buffer, this.uInt32_),
836
          dwBlockStart: this.readNumber(buffer, this.uInt32_),
837
          dwSampleOffset: this.readNumber(buffer, this.uInt32_),
838
        });
839
      }
840
    }
841
  }
842
843
  /**
844
   * Read the 'smpl' chunk of a wave file.
845
   * @param {!Uint8Array} buffer The wav file buffer.
846
   * @private
847
   */
848
  readSmplChunk_(buffer) {
849
    /** @type {?Object} */
850
    let chunk = this.findChunk('smpl');
851
    if (chunk) {
852
      this.head_ = chunk.chunkData.start;
853
      this.smpl.chunkId = chunk.chunkId;
854
      this.smpl.chunkSize = chunk.chunkSize;
855
      this.smpl.dwManufacturer = this.readNumber(buffer, this.uInt32_);
856
      this.smpl.dwProduct = this.readNumber(buffer, this.uInt32_);
857
      this.smpl.dwSamplePeriod = this.readNumber(buffer, this.uInt32_);
858
      this.smpl.dwMIDIUnityNote = this.readNumber(buffer, this.uInt32_);
859
      this.smpl.dwMIDIPitchFraction = this.readNumber(buffer, this.uInt32_);
860
      this.smpl.dwSMPTEFormat = this.readNumber(buffer, this.uInt32_);
861
      this.smpl.dwSMPTEOffset = this.readNumber(buffer, this.uInt32_);
862
      this.smpl.dwNumSampleLoops = this.readNumber(buffer, this.uInt32_);
863
      this.smpl.dwSamplerData = this.readNumber(buffer, this.uInt32_);
864
      for (let i = 0; i < this.smpl.dwNumSampleLoops; i++) {
865
        this.smpl.loops.push({
866
          dwName: this.readNumber(buffer, this.uInt32_),
867
          dwType: this.readNumber(buffer, this.uInt32_),
868
          dwStart: this.readNumber(buffer, this.uInt32_),
869
          dwEnd: this.readNumber(buffer, this.uInt32_),
870
          dwFraction: this.readNumber(buffer, this.uInt32_),
871
          dwPlayCount: this.readNumber(buffer, this.uInt32_),
872
        });
873
      }
874
    }
875
  }
876
877
  /**
878
   * Read the 'data' chunk of a wave file.
879
   * @param {!Uint8Array} buffer The wav file buffer.
880
   * @param {boolean} samples True if the samples should be loaded.
881
   * @throws {Error} If no 'data' chunk is found.
882
   * @private
883
   */
884
  readDataChunk_(buffer, samples) {
885
    /** @type {?Object} */
886
    let chunk = this.findChunk('data');
887
    if (chunk) {
888
      this.data.chunkId = 'data';
889
      this.data.chunkSize = chunk.chunkSize;
890
      if (samples) {
891
        this.data.samples = buffer.slice(
892
          chunk.chunkData.start,
893
          chunk.chunkData.end);
894
      }
895
    } else {
896
      throw Error('Could not find the "data" chunk');
897
    }
898
  }
899
900
  /**
901
   * Read the 'bext' chunk of a wav file.
902
   * @param {!Uint8Array} buffer The wav file buffer.
903
   * @private
904
   */
905
  readBextChunk_(buffer) {
906
    /** @type {?Object} */
907
    let chunk = this.findChunk('bext');
908
    if (chunk) {
909
      this.head_ = chunk.chunkData.start;
910
      this.bext.chunkId = chunk.chunkId;
911
      this.bext.chunkSize = chunk.chunkSize;
912
      this.bext.description = this.readString(buffer, 256);
913
      this.bext.originator = this.readString(buffer, 32);
914
      this.bext.originatorReference = this.readString(buffer, 32);
915
      this.bext.originationDate = this.readString(buffer, 10);
916
      this.bext.originationTime = this.readString(buffer, 8);
917
      this.bext.timeReference = [
918
        this.readNumber(buffer, this.uInt32_),
919
        this.readNumber(buffer, this.uInt32_)];
920
      this.bext.version = this.readNumber(buffer, this.uInt16_);
921
      this.bext.UMID = this.readString(buffer, 64);
922
      this.bext.loudnessValue = this.readNumber(buffer, this.uInt16_);
923
      this.bext.loudnessRange = this.readNumber(buffer, this.uInt16_);
924
      this.bext.maxTruePeakLevel = this.readNumber(buffer, this.uInt16_);
925
      this.bext.maxMomentaryLoudness = this.readNumber(buffer, this.uInt16_);
926
      this.bext.maxShortTermLoudness = this.readNumber(buffer, this.uInt16_);
927
      this.bext.reserved = this.readString(buffer, 180);
928
      this.bext.codingHistory = this.readString(
929
        buffer, this.bext.chunkSize - 602);
930
    }
931
  }
932
933
  /**
934
   * Read the 'ds64' chunk of a wave file.
935
   * @param {!Uint8Array} buffer The wav file buffer.
936
   * @throws {Error} If no 'ds64' chunk is found and the file is RF64.
937
   * @private
938
   */
939
  readDs64Chunk_(buffer) {
940
    /** @type {?Object} */
941
    let chunk = this.findChunk('ds64');
942
    if (chunk) {
943
      this.head_ = chunk.chunkData.start;
944
      this.ds64.chunkId = chunk.chunkId;
945
      this.ds64.chunkSize = chunk.chunkSize;
946
      this.ds64.riffSizeHigh = this.readNumber(buffer, this.uInt32_);
947
      this.ds64.riffSizeLow = this.readNumber(buffer, this.uInt32_);
948
      this.ds64.dataSizeHigh = this.readNumber(buffer, this.uInt32_);
949
      this.ds64.dataSizeLow = this.readNumber(buffer, this.uInt32_);
950
      this.ds64.originationTime = this.readNumber(buffer, this.uInt32_);
951
      this.ds64.sampleCountHigh = this.readNumber(buffer, this.uInt32_);
952
      this.ds64.sampleCountLow = this.readNumber(buffer, this.uInt32_);
953
      //if (wav.ds64.chunkSize > 28) {
954
      //  wav.ds64.tableLength = unpack(
955
      //    chunkData.slice(28, 32), uInt32_);
956
      //  wav.ds64.table = chunkData.slice(
957
      //     32, 32 + wav.ds64.tableLength);
958
      //}
959
    } else {
960
      if (this.container == 'RF64') {
961
        throw Error('Could not find the "ds64" chunk');
962
      }
963
    }
964
  }
965
966
  /**
967
   * Read the 'LIST' chunks of a wave file.
968
   * @param {!Uint8Array} buffer The wav file buffer.
969
   * @private
970
   */
971
  readLISTChunk_(buffer) {
972
    /** @type {?Object} */
973
    let listChunks = this.findChunk('LIST', true);
974
    if (listChunks !== null) {
975
      for (let j=0; j < listChunks.length; j++) {
976
        /** @type {!Object} */
977
        let subChunk = listChunks[j];
978
        this.LIST.push({
979
          chunkId: subChunk.chunkId,
980
          chunkSize: subChunk.chunkSize,
981
          format: subChunk.format,
982
          subChunks: []});
983
        for (let x=0; x<subChunk.subChunks.length; x++) {
984
          this.readLISTSubChunks_(subChunk.subChunks[x],
985
            subChunk.format, buffer);
986
        }
987
      }
988
    }
989
  }
990
991
  /**
992
   * Read the sub chunks of a 'LIST' chunk.
993
   * @param {!Object} subChunk The 'LIST' subchunks.
994
   * @param {string} format The 'LIST' format, 'adtl' or 'INFO'.
995
   * @param {!Uint8Array} buffer The wav file buffer.
996
   * @private
997
   */
998
  readLISTSubChunks_(subChunk, format, buffer) {
999
    if (format == 'adtl') {
1000
      if (['labl', 'note','ltxt'].indexOf(subChunk.chunkId) > -1) {
1001
        this.head_ = subChunk.chunkData.start;
1002
        /** @type {!Object<string, string|number>} */
1003
        let item = {
1004
          chunkId: subChunk.chunkId,
1005
          chunkSize: subChunk.chunkSize,
1006
          dwName: this.readNumber(buffer, this.uInt32_)
1007
        };
1008
        if (subChunk.chunkId == 'ltxt') {
1009
          item.dwSampleLength = this.readNumber(buffer, this.uInt32_);
1010
          item.dwPurposeID = this.readNumber(buffer, this.uInt32_);
1011
          item.dwCountry = this.readNumber(buffer, this.uInt16_);
1012
          item.dwLanguage = this.readNumber(buffer, this.uInt16_);
1013
          item.dwDialect = this.readNumber(buffer, this.uInt16_);
1014
          item.dwCodePage = this.readNumber(buffer, this.uInt16_);
1015
        }
1016
        item.value = this.readZSTR(buffer, this.head_);
1017
        this.LIST[this.LIST.length - 1].subChunks.push(item);
1018
      }
1019
    // RIFF INFO tags like ICRD, ISFT, ICMT
1020
    } else if(format == 'INFO') {
1021
      this.head_ = subChunk.chunkData.start;
1022
      this.LIST[this.LIST.length - 1].subChunks.push({
1023
        chunkId: subChunk.chunkId,
1024
        chunkSize: subChunk.chunkSize,
1025
        value: this.readZSTR(buffer, this.head_)
1026
      });
1027
    }
1028
  }
1029
1030
  /**
1031
   * Read the 'junk' chunk of a wave file.
1032
   * @param {!Uint8Array} buffer The wav file buffer.
1033
   * @private
1034
   */
1035
  readJunkChunk_(buffer) {
1036
    /** @type {?Object} */
1037
    let chunk = this.findChunk('junk');
1038
    if (chunk) {
1039
      this.junk = {
1040
        chunkId: chunk.chunkId,
1041
        chunkSize: chunk.chunkSize,
1042
        chunkData: [].slice.call(buffer.slice(
1043
          chunk.chunkData.start,
1044
          chunk.chunkData.end))
1045
      };
1046
    }
1047
  }
1048
1049
  /**
1050
   * Validate the bit depth.
1051
   * @return {boolean} True is the bit depth is valid.
1052
   * @throws {Error} If bit depth is invalid.
1053
   * @private
1054
   */
1055
  validateBitDepth_() {
1056
    if (!this.WAV_AUDIO_FORMATS[this.bitDepth]) {
1057
      if (parseInt(this.bitDepth, 10) > 8 &&
1058
          parseInt(this.bitDepth, 10) < 54) {
1059
        return true;
1060
      }
1061
      throw new Error('Invalid bit depth.');
1062
    }
1063
    return true;
1064
  }
1065
}
1066